'use strict'

let fs=require('fs');

let path= require('path');

let router=require('koa-router')();



function getEach (dir){
    let files=fs.readdirSync(dir);
    let controllerFiles=files.filter((name)=>{
        return name.endsWith('.js') && name!=='index.js'
    })
    return controllerFiles;
}


function regiest(files){
    files.forEach((item)=>{
        let tempath=path.join(__dirname,item);
        let  route=require(tempath);
        for(let key in route){
            let type=route[key][0];
            let fn=route[key][1];
            if(type==='get'){
                router.get(key,fn);
            }else if (type==='post'){
                router.post(key,fn);
            }else if (type==='delete'){
                router.delete(key,fn);
            }else if (type==='put'){
                router.put(key,fn);
            }
        }
    })
}

//暴露

module.exports=function(current){
    let dir=current ||__dirname;

    let controllerFiles=getEach(dir);

    regiest(controllerFiles);

    return router.routes();
}